package com.dpiinc.TechPage.api

import okhttp3.FormBody
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response


/**
 * 公共参数 拦截器
 * Created by X on 2018/7/24.
 */
class CommParamInterceptor : Interceptor {

    companion object {
        private const val KEY_APPID = "appId"
        private const val KEY_SERVER_VERSION = "serVer"
    }

    override fun intercept(chain: Interceptor.Chain): Response {
        var request = chain.request()
        //配置公共参数
        request = when (request.method()) {
            "GET" -> addGetParams(request)
            "POST" -> addPostParams(request)
            else -> request
        }
        return chain.proceed(request)
    }

    private fun addGetParams(request: Request): Request {
        val modifiedUrl = request.url().newBuilder()
                .addQueryParameter(KEY_APPID, ApiConstants.appId)
                .addQueryParameter(KEY_SERVER_VERSION, ApiConstants.serVer)
                .build()

        return request.newBuilder().url(modifiedUrl).build()
    }

    private fun addPostParams(request: Request): Request {

        return if (request.body() is FormBody) {
            val bodyBuilder = FormBody.Builder()
            var formBody = request.body() as FormBody
            for (i in 0 until formBody.size()) {
                bodyBuilder.addEncoded(formBody.encodedName(i), formBody.encodedValue(i))
            }
            formBody = bodyBuilder
                    .addEncoded(KEY_APPID, ApiConstants.appId)
                    .addEncoded(KEY_SERVER_VERSION, ApiConstants.serVer)
                    .build()
            request.newBuilder().post(formBody).build()
        } else {
            request
        }
    }
}